package com.mediacloud.app.newsmodule.fragment.ugc

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.FileProvider
import java.io.File

object CameraToolsKt {
    const val REQUEST_CODE=123023
    var file: File? = null

    /**
     *
     * 拍照或录像
     */
    fun useCamera(
        context: Activity,
        requestCode: Int,
        photo: Boolean = true
    ) {
        val intent = Intent()
        intent.addCategory(Intent.CATEGORY_DEFAULT)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        val fileName = if (photo) {
            intent.action = MediaStore.ACTION_IMAGE_CAPTURE
            System.currentTimeMillis().toString() + ".jpg"
        } else {
            intent.action = MediaStore.ACTION_VIDEO_CAPTURE
            System.currentTimeMillis().toString() + ".mp4"
        }
        val rootFile =
            File(Environment.getExternalStorageDirectory(), context.packageName + "/camera")
        if (!rootFile.exists()) {
            rootFile.mkdirs()
        }

        file = File(rootFile, fileName)
        file?.parentFile?.mkdirs()
        file?.setWritable(true)
        val authority = context.packageName + ".fileProvider"
        val fileUri = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            FileProvider.getUriForFile(context, authority, file!!)
        } else {
            Uri.fromFile(file)
        }

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
        context.startActivityForResult(intent, requestCode)

    }
}